<?php

namespace AgilePayments\UMFintech;

use AgilePayments\Config;
use AgilePayments\Tool;

class Service
{
    private $config;

    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    public function pay($order_no, $pay_price, $splitData)
    {
        $_url = 'https://b2b.umfintech.com/merAccess/consume/genaralOrder';
        $data = [
            'mer_id'        => $this->config->pay_type_config->mid,
//            'notify_url'    => $notify_url,
            'version'       => '1.0',
            'order_id'      => $order_no,
            'mer_date'      => date('Ymd'),
            'order_type'    => '2',
            'amount'        => $pay_price,// $pay_price,
            'order_channel' => '2',
            'split_cmd'     => $splitData,
        ];
        $result = json_decode(Util::httpPost($data, $_url),true);

        if ($result['meta']['ret_code'] == '0000'){

            return [
                'status'    => true,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => ['appPayRequest'=>$result['data']??[],'pay_type'=>$this->config->pay_type],
            ];
        }else{
            Tool::log($result['meta']['ret_msg'],'error');
            return [
                'status'    => false,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => ['appPayRequest'=>$result['data']??[],'pay_type'=>$this->config->pay_type],
            ];
        }
    }

    /**
     * @desc 支付宝小程序支付信息
     */
    public function getPayInfo($trade_no,$order_no,$amount,$openid,$notify, $goods_id = '',$goods_name = '')
    {
        $data = [
            'mer_id'	    => $this->config->pay_type_config->mid,
            'notify_url'	=> $notify,
            'version'	    => '1.0',
            'trade_no'	    => $trade_no,
            'mer_trace'	    => $order_no . '_pay',
            'pay_type'	    => 'ALIPAY',
            'sub_pay_type'  => 'ALIPAY',
            'user_ip'       => $this->getIP()??'',
            'consumer_id'   => $order_no . '_pay',
            'multiple_subject'  => '1',
            'openid'        => $openid,
            'appid'         => $this->config->pay_type_config->app_id,
            'amount'	    => $amount,
            'goods_inf'	    => $order_no,
            'remark'	    => $order_no,
        ];

        $_url = 'https://b2b.umfintech.com/merAccess/payment/wechatPlatformPay';
        $result = json_decode(Util::httpPost($data, $_url),true);
        if ($result['meta']['ret_code'] == '0000'){

            return [
                'status'    => true,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }else{
            Tool::log($result['meta']['ret_msg'],'error');
            return [
                'status'    => false,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }
    }

    
    public function getIP()
    {
        static $realip;
        if (isset($_SERVER)){
            if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])){
                $realip = $_SERVER["HTTP_X_FORWARDED_FOR"];
            } else if (isset($_SERVER["HTTP_CLIENT_IP"])) {
                $realip = $_SERVER["HTTP_CLIENT_IP"];
            } else {
                $realip = $_SERVER["REMOTE_ADDR"];
            }
        } else {
            if (getenv("HTTP_X_FORWARDED_FOR")){
                $realip = getenv("HTTP_X_FORWARDED_FOR");
            } else if (getenv("HTTP_CLIENT_IP")) {
                $realip = getenv("HTTP_CLIENT_IP");
            } else {
                $realip = getenv("REMOTE_ADDR");
            }
        }
        return $realip;
    }


    public function close($trade_no)
    {
        $_url = 'https://b2b.umfintech.com/merAccess/consume/closeOrder';

        $data = [
            'mer_id'	=> $this->config->pay_type_config->mid,
            'version'	=> '1.0',
            'mer_date'	=> date('Ymd'),
            'trade_no'	=> $trade_no,
        ];
        $result = json_decode(Util::httpPost($data, $_url),true);

        if ($result['meta']['ret_code'] == '0000'){
            return true;
        }else{
            Tool::log($result['meta']['ret_msg'],'error');
            return false;
        }
    }

    /**
     * @desc 查询
     * @param $trade_no
     * @return array
     */
    public function query($trade_no)
    {
        $_url = 'https://b2b.umfintech.com/merAccess/consume/orderQuery';

        $data = [
            'mer_id'	=> $this->config->pay_type_config->mid,
            'version'	=> '1.0',
            'mer_date'	=> date('Ymd'),
            'trade_no'	=> $trade_no,
        ];
        $result = json_decode(Util::httpPost($data, $_url),true);

        if ($result['meta']['ret_code'] == '0000'){
            return [
                'status'    => true,
                'msg'       => $result['meta']['ret_msg'],
                'data'      => $result['data']??[],
            ];
        }else{
            Tool::log($result['meta']['ret_msg'],'error');
            return [
                'status'    => false,
                'msg'       => $result['meta']['ret_msg'],
                'data'      => $result['data']??[],
            ];
        }
    }

    /**
     * @deac 退款查询
     * @param $refund_no
     * @param $date
     * @return array
     */
    public function refundQuery($refund_no, $trade_no = '', $date = '')
    {
        $_url = 'https://b2b.umfintech.com/merAccess/refund/orderInfo';

        $data = [
            'mer_id'	=> $this->config->pay_type_config->mid,
            'version'	=> '1.0',
            'mer_date'	=> $date,
            'order_id'	=> $refund_no,
        ];
        $result = json_decode(Util::httpGet($data, $_url),true);

        if ($result['meta']['ret_code'] == '0000'){
            return [
                'status'    => true,
                'msg'       => $result['meta']['ret_msg'],
                'data'      => $result['data']??[],
            ];
        }else{
            return [
                'status'    => false,
                'msg'       => $result['meta']['ret_msg'],
                'data'      => $result['data']??[],
            ];
        }
    }
    // TODO 是否确定使用后分账 还需更改 $split（分账详情）
    public function refund($payInfo, $notify = '')
    {
        $_url = 'https://b2b.umfintech.com/merAccess/refund/refundOrder';

        $data = [
            'mer_id'	        => $this->config->pay_type_config->mid,
            'version'	        => '1.0',
            'notify_url'        => $notify,
            'order_id'          => $payInfo['refund_order_no'],
            'mer_date'          => date("Ymd"),
            'amount'            => $payInfo['pay_amount'],
            'ori_order_id'      => $payInfo['out_order_id'],
            'ori_mer_date'      => date('Ymd',$payInfo['create_time']),
            'ori_mer_trace'     => $payInfo['out_order_id'].'_pay',
            'fee_payer'         => '1',
            'refund_cmd'        => $payInfo['split'],
        ];
        $result = json_decode(Util::httpPost($data, $_url),true);

        if ($result['meta']['ret_code'] == '0000'){
            return [
                'status'    => true,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }else{
            return [
                'status'    => false,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }
    }

    public function verifySign($request)
    {
        $sign = $request->header('SIGNATURE','');
        $plan = explode('&',$request->getInput())[1];
        if (Util::verifySign($plan, $sign)){  // 验签成功！
            $status = true;
        }else{
            $status = false;
        }
        $payOrderId = json_decode($plan,true)['data']['order_id'];//substr(json_decode($plan,true)['data']['order_id'],0,-4);
        return [
            'code'          => json_decode($plan,true)['meta']['ret_code']??'',
            'status'        => $status,
            'payOrderId'    => $payOrderId, // order_id
            'data'          => json_decode($plan,true)['data']??[],
            'trade_no'      => json_decode($plan,true)['data']['trade_no']??'',
            'query_id'      => json_decode($plan,true)['data']['queryId']??'',
        ];
    }

    public function getUserId($code)
    {
        $obj = new \AgilePayments\Alipay\Service($this->config);
        return $obj->getUserId($code);
    }

    public function finishOrder($trade_no, $notify_url = '')
    {
        $_url = 'https://b2b.umfintech.com/merAccess/consume/finishOrder';

        $data = [
            'mer_id'	=> $this->config->pay_type_config->mid,
            'version'	=> '1.0',
            'notify_url'=> $notify_url,
            'trade_no'  => $trade_no,
        ];
        $result = json_decode(Util::httpPost($data, $_url),true);

        if ($result['meta']['ret_code'] == '0000'){
            $status = true;
        }else{
            $status = false;
        }
        return [
            'status'        => $status,
            'msg'           => $result['meta']['ret_msg']??'',
        ];
    }


    /**
     * @deac 余额支付
     * @param string 支付账号 【1：结算用户，2：分佣账号】
     *
     */
    public function payByBalance($order_no, $trade_no, $amount, $remark = '', $notify_url = '', $type = '1')
    {
//        $result = array (
//            'meta' =>
//                array (
//                    'ret_code' => '0000',
//                    'ret_msg' => '支付成功',
//                ),
//            'data' =>
//                array (
//                    'mer_id' => '51328',
//                    'version' => '1.0',
//                    'mer_trace' => 'UMFTS5RZHA3639378488_pay',
//                    'trade_no' => '2308161159301971',
//                    'amount' => '1',
//                    'settle_amt' => '1',
//                    'mer_check_date' => '20230816',
//                    'ret_code' => NULL,
//                    'ret_msg' => NULL,
//                ),
//            'links' => NULL,
//        );
        if ($type == '1'){
            $user_id = Tool::env('UMFintechPay.settUserId');
        }else{
            $user_id = Tool::env('UMFintechPay.commUserId');
        }
        $_url = 'https://b2b.umfintech.com/merAccess/consume/balance';
        $data = [
            'mer_id'	    => $this->config->pay_type_config->mid,
            'notify_url'    => $notify_url,
            'version'	    => '1.0',
            'trade_no'      => $trade_no,
            'mer_trace'     => $order_no . '_pay',
            'user_id'       => $user_id,
            'amount'        => $amount,
            'remark'        => $remark,
        ];
        $result = json_decode(Util::httpPost($data, $_url),true);
        if ($result['meta']['ret_code'] == '0000'){
            $status = true;
        }else{
            $status = false;
        }
        return [
            'status' => $status,
            'msg'   => $result['meta']['ret_msg'],
            'data'  => $result,
        ];
    }

    /**
     * @desc 银行卡支付信息（接口一）
     */
    public function getCardInfo($trade_no, $order_no, $amount, $card_id, $notify, $bindCard = false)
    {
        $user_id = Tool::env('UMFintechPay.settUserId');
        $data = [
            'mer_id'	    => $this->config->pay_type_config->mid,
            'notify_url'	=> $notify,
            'version'	    => '1.0',
            'trade_no'	    => $trade_no,
            'mer_cust_id'   => $user_id,
            'mer_trace'	    => $order_no . '_pay',
            'amount'	    => $amount,
        ];
        if ($bindCard == false){
            $data['card_id'] = Util::encrypt($card_id);
        }else{
            $data['p_agreement_id'] = $bindCard['p_agreement_id'];
        }

        $_url = 'https://b2b.umfintech.com/merAccess/payment/quick/order';
        $result = json_decode(Util::httpPost($data, $_url),true);
        if ($result['meta']['ret_code'] == '0000'){
            return [
                'status'    => true,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }else{
            return [
                'status'    => false,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }
        
    }

    /**
     * 获取银行卡支付验证码
     */
    public function getCardCaptcha($notify_url, $trade_no, $mer_trace, $mobile, $card_id, $card_holder, $identity_code, $valid_date, $cvv2, $bindCard = false)
    {
        $user_id = Tool::env('UMFintechPay.settUserId');
        $data = [
            'mer_id'	    => $this->config->pay_type_config->mid,
            'notify_url'	=> $notify_url,
            'version'	    => '1.0',
            'trade_no'	    => $trade_no,
            'mer_trace'	    => $mer_trace,
            'bank_mobile_id'=> $mobile,
        ];
        if ($bindCard == false){
            $data['card_id']        = Util::encrypt($card_id);
            $data['card_holder']    = Util::encrypt($card_holder);
            $data['identity_type']  = '1';
            $data['identity_code']  = Util::encrypt($identity_code);
            $data['valid_date']     = Util::encrypt($valid_date);
            $data['cvv2']           = Util::encrypt($cvv2);
        }else{
            $data['p_agreement_id'] = $bindCard['p_agreement_id'];
        }

        $_url = 'https://b2b.umfintech.com/merAccess/payment/quick/verifyCode';
        $result = json_decode(Util::httpPost($data, $_url),true);
        if ($result['meta']['ret_code'] == '0000'){
            return [
                'status'    => true,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }else{
            return [
                'status'    => false,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }
    }

    /**
     * @desc 银行卡支付-确认支付
     */
    public function quickConfirm($amount, $verifyCode, $notify_url, $trade_no, $mer_trace, $mobile, $card_id, $card_holder, $identity_code, $valid_date, $cvv2, $bindCard = false)
    {
        $user_id = Tool::env('UMFintechPay.settUserId');
        $data = [
            'mer_id'	    => $this->config->pay_type_config->mid,
            'notify_url'	=> $notify_url,
            'version'	    => '1.0',
            'trade_no'	    => $trade_no,
            'mer_trace'	    => $mer_trace,
            'amount'        => $amount,
            'bank_mobile_id'=> $mobile,
            'verify_code'   => $verifyCode,
        ];
        if ($bindCard == false){
            $data['card_id']        = Util::encrypt($card_id);
            $data['card_holder']    = Util::encrypt($card_holder);
            $data['identity_type']  = '1';
            $data['identity_code']  = Util::encrypt($identity_code);
            $data['valid_date']     = Util::encrypt($valid_date);
            $data['cvv2']           = Util::encrypt($cvv2);
        }else{
            $data['p_agreement_id'] = $bindCard['p_agreement_id'];
        }

        $_url = 'https://b2b.umfintech.com/merAccess/payment/quick/confirm';
        $result = json_decode(Util::httpPost($data, $_url),true);
        if ($result['meta']['ret_code'] == '0000'){
            return [
                'status'    => true,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }else{
            return [
                'status'    => false,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }

    }

    public function returnSuccess()
    {
        echo '{"meta":{"ret_code":"0000"}}';
    }

    public function payByBalanceRefund($order_no, $trade_no, $amount, $remark = '', $notify_url = '', $umf_user_id = '')
    {
        $_url = 'https://b2b.umfintech.com/merAccess/consume/balance';
        $data = [
            'mer_id'	    => $this->config->pay_type_config->mid,
            'notify_url'    => $notify_url,
            'version'	    => '1.0',
            'trade_no'      => $trade_no,
            'mer_trace'     => $order_no . '_pay',
            'user_id'       => $umf_user_id,
            'amount'        => $amount,
            'remark'        => $remark,
        ];
        $result = json_decode(Util::httpPost($data, $_url),true);
        if ($result['meta']['ret_code'] == '0000'){
            $status = true;
        }else{
            $status = false;
        }
        return [
            'status' => $status,
            'msg'   => $result['meta']['ret_msg'],
            'data'  => $result,
        ];
    }

    /**
     * @deac 联动网银支付
     * @param $amount
     * @param $notify
     * @param $retUrl
     * @param $trade_no
     * @param $order_no
     * @param $pay_type
     * @param $gate_id
     * @param $expire_time
     * @return array
     */
    public function payByEbank($amount, $notify, $retUrl, $trade_no, $order_no, $pay_type, $gate_id, $expire_time)
    {
        $data = [
            'mer_id'        => $this->config->pay_type_config->mid,
            'notify_url'    => $notify,
            'ret_url'       => $retUrl,
            'version'       => '1.0',
            'trade_no'      => $trade_no,
            'mer_trace'     => $order_no . '_pay',
            'pay_type'      => $pay_type,
            'gate_id'       => $gate_id,
            'amount'        => $amount,
            'expire_time'   => $expire_time,
        ];

        $_url = 'https://b2b.umfintech.com/merAccess/payment/ebank';
        return json_decode(Util::httpPost($data, $_url),true);

    }

    /**
     * @deac 子账户充值
     */
    public function rechargeOrder($user_id, $amount, $order_id, $notify_url)
    {
        $data = [
            'mer_id'        => $this->config->pay_type_config->mid,
            'version'       => '1.0',
            'mer_date'      => date('Ymd'),
            'order_id'      => $order_id,
            'amount'        => $amount,
            'in_user_id'    => $user_id,
            'notify_url'    => $notify_url,
        ];
        $_url = 'https://b2b.umfintech.com/merAccess/recharge/order';
        $result = json_decode(Util::httpPost($data, $_url),true);
        if ($result['meta']['ret_code'] == '0000'){
            return [
                'status'    => true,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }else{
            return [
                'status'    => false,
                'msg'       => $result['meta']['ret_msg']??'',
                'data'      => $result['data']??[],
            ];
        }

    }

}